# blame: christopher taylor (christopher(dot)paul(dot)taylor(at)gmail(dot)com
# released under terms of MPL (Mozilla Public License) 1.1 http://www.mozilla.org/MPL/
#
from time import *
import pickle

import scipy
from scipy.cluster import *
from scipy.cluster.hierarchy import *

import matplotlib.pyplot

from SongVec import *

class DeDup:
	def __init__(self, songvecs):
		self.mat = [ [ 0 for i in range(0, len(songvecs)) ] for j in range(0, len(songvecs)) ]
		self.songvecs = songvecs
		
	def calcTagSpace(self):
		for i in range(0, len(self.songvecs)):
			orig_songvec = self.songvecs[i]
			for j in range(0, len(self.songvecs)):
				curr_songvec = self.songvecs[j]
				eddist = orig_songvec.edit_distance(curr_songvec)
				self.mat[i][j] = SongVec.vec_length(eddist)
			
		return self.mat
		
if __name__ == "__main__":
	print "creating songvecs"
	songvecs, songvec_tups = SongVecLoader.load("F:\Media\My Music")
	print "%d songvecs created" % (len(songvecs), )
	
	"creating deduper"
	dedup = DeDup(songvecs)
	"deduper created"
	
	print "creating tag_space"
	prev_time = time()
	tag_space = dedup.calcTagSpace()
	curr_time = time()
	print ("tag_space created in ", curr_time - prev_time)
	
	fd = open("tag_space.pkl", "w")
	pickle.dump(tag_space, fd)
	fd.close()
	
	print "creating clusters"
	ts = hierarchy.single(tag_space)
	print "clusters created"
	
	clusterNodeTree = to_tree(ts)
	
	print "creating dendrogram"
	ts = hierarchy.dendrogram(ts)
	print "dendrogram created"
	
	#fd = open("dendrogram.pkl", "w")
	#pickle.dump(ts, fd)
	#fd.close()
	
	print ts
	
	#for i in range(0, len(songvecs)):
	#	print i, songvecs[i].file_name
	matplotlib.pylab.show()
	
	
